package com.xxxx.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.xxxx.seckill.exception.GlobalException;
import com.xxxx.seckill.mapper.UserMapper;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.service.IUserService;
import com.xxxx.seckill.utils.MD5Util;
import com.xxxx.seckill.vo.LoginVo;
import com.xxxx.seckill.vo.RespBean;
import com.xxxx.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lulongfei
 * @since 2022-04-20
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;

    /**
     * 登录
     *
     * @param loginVo  登录信息
     * @param request  请求体
     * @param response 响应体
     * @return RespBean
     */
    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        //获取手机号
        String mobile = loginVo.getMobile();
        //获取密码
        String password = loginVo.getPassword();
        //获取用户
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("mobile", mobile));
        //判断是否为空
        if (ObjectUtils.isEmpty(user)) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }
        //判断密码是否正确
        if (!MD5Util.formPassToDBPass(password, user.getSalt()).equals(user.getPassword())) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);

        }
//        //生成cookie
//        String ticket = UUIDUtil.uuid();
        //将用户信息存入redis中
//        redisTemplate.opsForValue().set("user:" + ticket, user);
//        request.getSession().setAttribute(ticket, user);
//        CookieUtil.setCookie(request, response, "userTicket", ticket);
        return RespBean.success();
    }

    /**
     * 根据Cookie获取用户
     *
     * @param userTicket
     * @return
     */
//    @Override
//    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
//        if (StringUtils.isEmpty(userTicket)) {
//            return null;
//        }
//        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
//        if (user != null) {
//            CookieUtil.setCookie(request, response, "userTicket", userTicket);
//        }
//        return user;
//    }

    /**
     * 更改密码
     *
     * @param userTicket
     * @param password
     * @param request
     * @param response
     * @return
     */
//    @Override
//    public RespBean updatePassword(String userTicket, String password, HttpServletRequest request, HttpServletResponse response) {
//        User user = getUserByCookie(userTicket, request, response);
//        if (user == null) {
//            throw new GlobalException(RespBeanEnum.MOBILE_NOT_EXIST);
//        }
//        user.setPassword(MD5Util.inputPassToDBPass(password, user.getSalt()));
//        int result = userMapper.updateById(user);
//        if (1 == result) {
//            //删除Redis
//            redisTemplate.delete("user:" + userTicket);
//            return RespBean.success();
//        }
//        return RespBean.error(RespBeanEnum.PASSWORD_UPDATE_FAIL);
//    }

    @Override
    public RespBean doCache() throws IOException {
        List<User> userList = userService.list();
        log.info("当前用户数量为：{}",userList.size());
        File file = new File("/Users/cookr/Desktop/config.txt");
        if (file.exists()) {
            file.delete();
        }
        List<List<User>> partition = Lists.partition(userList, 1000);
        String rowAll = "";
        Integer i = 0;
        Integer j = 0;

        for (List<User> users : partition) {
            log.info("当前循环为：{}",i);
            //优化思路 提取此方法 做异步
            for (User user : users) {
                log.info("当前执行第{}循环，第{} 个",i,j);
                String ticket = "11111";
                String row = user.getId() + "," + ticket+"\r\n";
                redisTemplate.opsForValue().set("user:" + ticket, user);
                log.info("当前文件数据为：{}",row);
                rowAll = rowAll + row;
                j++;
            }
            i++;
        }
        RandomAccessFile raf = new RandomAccessFile(file, "rw");

        raf.write(rowAll.getBytes());
        raf.close();
        return null;
    }
}
